//
//  UserAccount.swift
//  SinaBlog
//
//  Created by ChenWei on 15/10/24.
//  Copyright © 2015年 cw. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    /*
    *  "access_token" = "2.00qwd6PDvA3QLB16c76a46c50IUmpe";
    "expires_in" = 157679999;
    "remind_in" = 157679999;
    uid = 2976155300;
    */
    
    var access_token: String?
    var expires_in: NSNumber? {
        didSet {
            // 根据过期秒数,计算真正的过期时间
            expires_date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        }
    }
    /// 当前授权用户的UID
    var uid: String?
    /// 记录真正的过期时间
    var expires_date: NSDate?
    /// 用户头像
    var avatar_large: String?
    /// 用户昵称
    var screen_name: String?
    
    init(dict: [String: AnyObject]) {
    
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
   
    
    static let keys = ["access_token", "expires_in", "uid", "expires_date", "avatar_large", "screen_name"]
    override var description:String {
        return "\(dictionaryWithValuesForKeys(UserAccount.keys))"
    }
    
    // MARK: - 外部控制方法
    /// 获取用户信息
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> ()){
        
        // 1.定义URL
        let URL = "2/users/show.json"
        // 2.设置参数
        let parmas = ["access_token": access_token!, "uid":uid!]
        // 2.利用AFN发送网络请求
        NetworkTools.shareNetworkTools().GET(URL, parameters: parmas, success: { (_, dict) -> Void in

            self.avatar_large = (dict["avatar_large"] as! String)
            self.screen_name = (dict["screen_name"] as! String)
            
            // 保存用户模型
//            self.saveAccount()
            finished(account: self, error: nil)
            }) { (_, error) -> Void in
                
             finished(account: nil, error: nil)
        }
        
    }
    /// 授权模型保存路径
    private static let path = "account.plist".cacheDir()
    
    /// 保存授权模型
    func saveAccount() {
        NSLog(UserAccount.path)
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.path)
    }
    /// 读取模型数据
    static var account: UserAccount?
    class func loadAccount() -> UserAccount? {
        // 1.加载授权信息
        if account == nil {
            NSLog(message: "从文件中加载授权信息")
            account = (NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.path) as? UserAccount)
        }
        
        // 2.处理过期时间
        if account != nil {
            if account!.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
                account = nil
            }
        }
        return account
    }
    
    // MARK: - NSCodeing
    /// 写入到文件 -> 序列化
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(avatar_large, forKey:"avatar_large")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
    }
    
    /// 从文件中读取 -> 反序列化
    required init?(coder aDecoder: NSCoder) {
        access_token = (aDecoder.decodeObjectForKey("access_token") as? String)
        expires_in = (aDecoder.decodeObjectForKey("expires_in") as? NSNumber)
        expires_date = (aDecoder .decodeObjectForKey("expires_date") as? NSDate)
        uid = (aDecoder.decodeObjectForKey("uid") as? String)
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
}
